OOP
Encapsulation
- Hide internal details and expose only what is necessary.
- Ususally define getter and setter for a value instead of fetching it directly for a class.
- Benefit
- Protects internal state and maintains control over how it's accessed or modified.
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number) {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
Inheritance
- Allows a class to inherit properties and methods from another class.
- Types
- Single
- One child class inherits from one parent class.
- class a extends b
- Multilevel
- A class inherits from a derived class which itself inherited from another.
- class a extends b
- class c extends a
- Hierarchical
- Multiple classes inherit from the same parent class.
- class a extends b
- class c extends b
- Multiple (Not supportef in TS, JAVA)
- One class inherits from more than one class — TypeScript/JavaScript do not support this directly due to ambiguity (diamond problem).
- class a extends b,c
- diamond problem is if both class b and c have same function then will not know on extend which one to preserve.
- Single
- Benefit is it increases code reusability.
Polymorphism
-
Polymorphism allows the same method name to behave differently depending on the class.
-
Makes code extensible and flexible for future changes.
-
Types
-
Compile Time(Function overloading)
- Same method name with different parameters in the same class.
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
String add(String a, String b) {
return a + b;
}
} -
Run Time(Method overloading)
- Subclasses override parent class methods.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Reference of parent, object of child
a.sound(); // Output: Dog barks (child method is called)
}
}
-
Abstraction
- Defines what an object does, not how it does it.
- Hides implementation details and exposes only the interface.
abstract class Shape {
abstract getArea(): number;
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
}